package com.xiaoyu.net.util;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

import com.xiaoyu.net.secret.RSAUtil;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.TreeMap;

import in.srain.cube.request.RequestData;
import in.srain.cube.util.CLog;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;

/**
 * 网络相关辅助类
 * Created by Yancy on 2015/9/24.
 */
public class NetUtils {

    private static final String DEFAULT_TOKEN = "default";

    private NetUtils() {
        throw new UnsupportedOperationException("cannot be instantiated");
    }

    /**
     * 判断网络是否连接
     *
     * @return true 连网；  false 没连网
     */
    public static boolean isConnected(Context context, Boolean isShow) {

        ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        if (null != connectivity) {
            NetworkInfo info = connectivity.getActiveNetworkInfo();
            if (null != info && info.isConnected()) {
                if (info.getState() == NetworkInfo.State.CONNECTED) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 判断是否是wifi连接
     *
     * @return true:wifi 连接，false wifi没连接
     */
    public static boolean isWifi(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm == null)
            return false;
        return cm.getActiveNetworkInfo().getType() == ConnectivityManager.TYPE_WIFI;

    }

    /**
     * 打开网络设置界面
     *
     * @param activity activity_launch
     */
    public static void openSetting(Activity activity) {
        Intent intent = new Intent("/");
        ComponentName cm = new ComponentName("com.android.settings", "com.android.settings.WirelessSettings");
        intent.setComponent(cm);
        intent.setAction("android.intent.action.VIEW");
        activity.startActivityForResult(intent, 0);
    }

    public static String buildSign(String appKey, String method, String url, Map<String, Object> query, Map<String, Object> body, String secretKey) {
        Map<String, Object> signQuery = new TreeMap<>();
        signQuery.put("api", url);
        signQuery.put("appKey", appKey);
        signQuery.put("method", method);

        if (query != null && !query.isEmpty()) {
            signQuery.putAll(query);
        }
        if (body != null && !body.isEmpty()) {
            signQuery.putAll(body);
        }

        signQuery.remove("token");
        // when a request is resent, token will be brought in to the query
        signQuery.remove("sign");

        final String queryString = RequestData.buildQueryString(signQuery, url, false);
        try {
            final String sign = sha1(queryString + secretKey);
//            final String sign = RSAUtil.encryptPublic(queryString, secretKey);
            CLog.d("RequestProvider", "buildSign: sign_str: %s, secret_key: %s, sign: %s", queryString, secretKey, sign);
            return sign;
        } catch (Exception e) {
            CLog.d("RequestProvider", "buildSign: error, sign_str: %s, secret_key: %s", queryString, secretKey);
            e.printStackTrace();
        }
        return DEFAULT_TOKEN;
    }

    private static String convertToHex(byte[] data) {
        StringBuilder buf = new StringBuilder();
        for (byte b : data) {
            int halfByte = (b >>> 4) & 0x0F;
            int twoHalves = 0;
            do {
                buf.append((0 <= halfByte) && (halfByte <= 9) ? (char) ('0' + halfByte) : (char) ('a' + (halfByte - 10)));
                halfByte = b & 0x0F;
            } while (twoHalves++ < 1);
        }
        return buf.toString();
    }

    private static String sha1(String text) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        byte[] textBytes = text.getBytes(StandardCharsets.UTF_8);
        md.update(textBytes, 0, textBytes.length);
        byte[] sha1hash = md.digest();
        return convertToHex(sha1hash);
    }

    public static String readResponseString(Response response) {
        ResponseBody responseBody = response.body();
        if (responseBody != null) {
            BufferedSource source = responseBody.source();
            try {
                source.request(Long.MAX_VALUE);
                // clone buffer before reading from it
                Buffer buffer = source.getBuffer();
                return buffer.clone().readString(StandardCharsets.UTF_8);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "";
    }
}
